#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import pymysql

from wingman import logger
from wingman.common.error import ErrorCode
# from config.rules_help import MYSQL_HELP
from config.system import (
    MYSQL_DEV_DB, MYSQL_DEV_HOST, MYSQL_DEV_PORT, MYSQL_DEV_USER, MYSQL_DEV_PASSWD,
    MYSQL_TEST_DB, MYSQL_TEST_HOST, MYSQL_TEST_PORT, MYSQL_TEST_USER, MYSQL_TEST_PASSWD,
    MYSQL_PRE_DB, MYSQL_PRE_HOST, MYSQL_PRE_PORT, MYSQL_PRE_USER, MYSQL_PRE_PASSWD,
    MYSQL_PROD_DB, MYSQL_PROD_HOST, MYSQL_PROD_PORT, MYSQL_PROD_USER, MYSQL_PROD_PASSWD,
    MYSQL_LOCAL_DB, MYSQL_LOCAL_HOST, MYSQL_LOCAL_PORT, MYSQL_LOCAL_USER, MYSQL_LOCAL_PASSWD,
)


class CustomMysql:

    def __init__(self, env_name="local"):
        self.env_name = env_name
        credentials = {
            "dev": (MYSQL_DEV_DB, MYSQL_DEV_HOST, MYSQL_DEV_PORT, MYSQL_DEV_USER, MYSQL_DEV_PASSWD),
            "test": (MYSQL_TEST_DB, MYSQL_TEST_HOST, MYSQL_TEST_PORT, MYSQL_TEST_USER, MYSQL_TEST_PASSWD),
            "pre": (MYSQL_PRE_DB, MYSQL_PRE_HOST, MYSQL_PRE_PORT, MYSQL_PRE_USER, MYSQL_PRE_PASSWD),
            "prod": (MYSQL_PROD_DB, MYSQL_PROD_HOST, MYSQL_PROD_PORT, MYSQL_PROD_USER, MYSQL_PROD_PASSWD),
            "local": (MYSQL_LOCAL_DB, MYSQL_LOCAL_HOST, MYSQL_LOCAL_PORT, MYSQL_LOCAL_USER, MYSQL_LOCAL_PASSWD)
        }

        if self.env_name in credentials:
            MYSQL_DB, MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWD = credentials[self.env_name]
        else:
            MYSQL_DB, MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWD = credentials["test"]

        try:
            self.conn = pymysql.connect(database=MYSQL_DB, host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWD, port=MYSQL_PORT)
            self.cursor = self.conn.cursor()
        except Exception as e:
            logger.error(ErrorCode.MYSQL_DB_ERROR.value, str(e), __name__)

    def get_modify(self, modify, data, env_name):
        with self.conn.cursor() as cursor:
            if data:  # 添加检查,确保有数据时才使用参数化查询
                try:
                    cursor.execute(modify, data)
                    result = self.conn.commit()
                except Exception as e:
                    logger.error(ErrorCode.MYSQL_DB_ERROR.value, str(e), __name__)
                    return e
            else:  # 如果没有数据,直接执行 SQL
                try:
                    cursor.execute(modify)
                    result = cursor.fetchone()  # 获取查询结果的第一行
                    return result[0]
                except Exception as e:
                    logger.error(ErrorCode.MYSQL_DB_ERROR.value, str(e), __name__)
                    return e
        return result


if __name__ == '__main__':

    db_obj = CustomMysql()  # 创建DB_Obj的实例
    status_dict = db_obj.routine()
    print(f"创建的线程:{status_dict}")
